// 渠道配置模板数据
import { paymentChannels } from './channels'

export interface ChannelConfigField {
  fieldKey: string
  fieldName: string
  fieldType: 'input' | 'password' | 'select' | 'textarea' | 'upload'
  required: boolean
  placeholder?: string
  description?: string
  options?: { label: string; value: string }[]
  validation?: {
    pattern?: string
    minLength?: number
    maxLength?: number
    message?: string
  }
}

export interface TemplateConfigSection {
  sectionKey: string
  sectionName: string
  description?: string
  icon?: string
  order?: number
  collapsed?: boolean
  fields: ChannelConfigField[]
}

export interface ChannelConfigTemplate {
  channelId: string
  channelName: string
  channelCode: string
  iconUrl: string
  configFields: ChannelConfigField[]  // 保留向后兼容
  configSections?: TemplateConfigSection[]  // 新增分区支持
  testConnection: boolean
  description?: string
}

export interface ProductConfig {
  productId: string
  productName: string
  productCode: string
  enabled: boolean
  feeRate: number
  minAmount: number
  maxAmount: number
  dailyLimit?: number
  monthlyLimit?: number
  settlementCycle: string
  description?: string
}

export interface ServiceProviderChannelConfig {
  id: string
  providerId: string
  channelId: string
  channelName: string
  enabled: boolean
  configData: Record<string, any>
  status: 'ACTIVE' | 'INACTIVE' | 'TESTING' | 'ERROR'
  lastTestTime?: string
  lastTestResult?: 'SUCCESS' | 'FAILED'
  errorMessage?: string
  createdTime: string
  updatedTime: string
}

import { protocol3Manager } from './protocol3-manager'
import { FieldType } from '../types/protocol3-types'

// 协议字段类型到模板字段类型的映射
const fieldTypeMapping: Record<FieldType, ChannelConfigField['fieldType']> = {
  [FieldType.INPUT]: 'input',
  [FieldType.PASSWORD]: 'password',
  [FieldType.TEXTAREA]: 'textarea',
  [FieldType.SELECT]: 'select',
  [FieldType.UPLOAD]: 'upload',
  [FieldType.URL]: 'input', // URL字段作为input处理
  [FieldType.NUMBER]: 'input',
  [FieldType.CHECKBOX]: 'select', // 复选框转为选择框
  [FieldType.RADIO]: 'select',
  [FieldType.DATE]: 'input',
  [FieldType.DATETIME]: 'input',
  [FieldType.TIME]: 'input'
}

// 根据协议字段转换为模板字段
function convertProtocolFieldToTemplateField(protocolField: any): ChannelConfigField {
  const templateField: ChannelConfigField = {
    fieldKey: protocolField.fieldKey,
    fieldName: protocolField.fieldName,
    fieldType: fieldTypeMapping[protocolField.fieldType] || 'input',
    required: protocolField.required || false,
    placeholder: protocolField.placeholder || `请输入${protocolField.fieldName}`,
    description: protocolField.description
  }

  // 处理选择框选项
  if (protocolField.options && protocolField.options.length > 0) {
    templateField.options = protocolField.options
  }

  // 处理验证规则
  if (protocolField.validation) {
    templateField.validation = {
      pattern: protocolField.validation.pattern,
      minLength: protocolField.validation.minLength,
      maxLength: protocolField.validation.maxLength,
      message: protocolField.validation.message
    }
  }

  return templateField
}

// 根据协议分区生成模板分区
function convertProtocolSectionToTemplateSection(protocolSection: any): TemplateConfigSection {
  return {
    sectionKey: protocolSection.sectionKey,
    sectionName: protocolSection.sectionName,
    description: protocolSection.description,
    icon: protocolSection.icon,
    order: protocolSection.order || 0,
    collapsed: protocolSection.collapsed || false,
    fields: protocolSection.fields.map((field: any) => convertProtocolFieldToTemplateField(field))
  }
}

// 根据渠道代码和协议生成配置字段
const generateConfigFields = (channelCode: string): ChannelConfigField[] => {
  try {
    // 获取渠道协议
    const protocolId = protocol3Manager.getProtocolByConvention(channelCode, 'MERCHANT_CHANNEL_CONFIG_V3')
    const protocol = protocol3Manager.getProtocol(protocolId)
    if (!protocol) {
      throw new Error(`找不到渠道 ${channelCode} 的协议配置`)
    }

    const configFields: ChannelConfigField[] = []

    // 遍历协议的配置分区，提取所有字段
    for (const section of protocol.configSections) {
      for (const field of section.fields) {
        const templateField = convertProtocolFieldToTemplateField(field)
        configFields.push(templateField)
      }
    }

    return configFields
  } catch (error) {
    console.warn(`无法获取渠道 ${channelCode} 的协议，使用默认配置:`, error)

    // 备用的通用配置
    return [
      {
        fieldKey: 'merchantId',
        fieldName: '商户号',
        fieldType: 'input',
        required: true,
        placeholder: '请输入商户号'
      },
      {
        fieldKey: 'apiKey',
        fieldName: 'API密钥',
        fieldType: 'password',
        required: true,
        placeholder: '请输入API密钥'
      },
      {
        fieldKey: 'secretKey',
        fieldName: '签名密钥',
        fieldType: 'password',
        required: false,
        placeholder: '请输入签名密钥（可选）'
      },
      {
        fieldKey: 'notifyUrl',
        fieldName: '回调地址',
        fieldType: 'input',
        required: false,
        placeholder: '请输入回调通知地址'
      },
      {
        fieldKey: 'sandboxMode',
        fieldName: '运行模式',
        fieldType: 'select',
        required: true,
        options: [
          { label: '生产环境', value: 'false' },
          { label: '沙箱环境', value: 'true' }
        ]
      }
    ]
  }
}

// 根据渠道代码和协议生成配置分区
const generateConfigSections = (channelCode: string): TemplateConfigSection[] => {
  try {
    // 获取渠道协议
    const protocolId = protocol3Manager.getProtocolByConvention(channelCode, 'MERCHANT_CHANNEL_CONFIG_V3')
    const protocol = protocol3Manager.getProtocol(protocolId)
    if (!protocol) {
      throw new Error(`找不到渠道 ${channelCode} 的协议配置`)
    }

    // 转换协议分区为模板分区
    return protocol.configSections
      .map(section => convertProtocolSectionToTemplateSection(section))
      .sort((a, b) => (a.order || 0) - (b.order || 0))

  } catch (error) {
    console.warn(`无法获取渠道 ${channelCode} 的协议分区，使用默认分区:`, error)

    // 备用的默认分区配置
    return [
      {
        sectionKey: 'basic',
        sectionName: '基础配置',
        description: '基本的商户信息和密钥配置',
        icon: 'SettingOutlined',
        order: 1,
        collapsed: false,
        fields: [
          {
            fieldKey: 'merchantId',
            fieldName: '商户号',
            fieldType: 'input',
            required: true,
            placeholder: '请输入商户号'
          },
          {
            fieldKey: 'apiKey',
            fieldName: 'API密钥',
            fieldType: 'password',
            required: true,
            placeholder: '请输入API密钥'
          },
          {
            fieldKey: 'secretKey',
            fieldName: '签名密钥',
            fieldType: 'password',
            required: false,
            placeholder: '请输入签名密钥（可选）'
          }
        ]
      },
      {
        sectionKey: 'advanced',
        sectionName: '高级配置',
        description: '回调地址和环境配置',
        icon: 'ToolOutlined',
        order: 2,
        collapsed: true,
        fields: [
          {
            fieldKey: 'notifyUrl',
            fieldName: '回调地址',
            fieldType: 'input',
            required: false,
            placeholder: '请输入回调通知地址'
          },
          {
            fieldKey: 'sandboxMode',
            fieldName: '运行模式',
            fieldType: 'select',
            required: true,
            options: [
              { label: '生产环境', value: 'false' },
              { label: '沙箱环境', value: 'true' }
            ]
          }
        ]
      }
    ]
  }
}

// 动态生成渠道配置模板（基于channels.ts数据）
const generateChannelConfigTemplates = (): ChannelConfigTemplate[] => {
  return paymentChannels.map(channel => ({
    channelId: channel.channelId,
    channelName: channel.channelName,
    channelCode: channel.channelCode,
    iconUrl: channel.iconUrl,
    description: `${channel.channelName}支付接口配置`,
    testConnection: true,
    configFields: generateConfigFields(channel.channelCode), // 保留向后兼容
    configSections: generateConfigSections(channel.channelCode) // 新增分区支持
  }))
}

// 渠道配置模板（懒加载，避免在模块加载时就调用protocol3Manager）
let _channelConfigTemplates: ChannelConfigTemplate[] | null = null

// 获取渠道配置模板（懒加载）
export function getChannelConfigTemplates(): ChannelConfigTemplate[] {
  if (!_channelConfigTemplates) {
    try {
      _channelConfigTemplates = generateChannelConfigTemplates()
    } catch (error) {
      console.warn('生成渠道配置模板失败，使用默认模板:', error)
      // 使用默认模板作为兜底
      _channelConfigTemplates = paymentChannels.map(channel => ({
        channelId: channel.channelId,
        channelName: channel.channelName,
        channelCode: channel.channelCode,
        iconUrl: channel.iconUrl,
        description: `${channel.channelName}支付接口配置`,
        testConnection: true,
        configFields: [
          {
            fieldKey: 'merchantId',
            fieldName: '商户号',
            fieldType: 'input',
            required: true,
            placeholder: '请输入商户号'
          },
          {
            fieldKey: 'apiKey',
            fieldName: 'API密钥',
            fieldType: 'password',
            required: true,
            placeholder: '请输入API密钥'
          }
        ],
        configSections: [
          {
            sectionKey: 'basic',
            sectionName: '基础配置',
            description: '基本的商户信息和密钥配置',
            order: 1,
            collapsed: false,
            fields: [
              {
                fieldKey: 'merchantId',
                fieldName: '商户号',
                fieldType: 'input',
                required: true,
                placeholder: '请输入商户号'
              },
              {
                fieldKey: 'apiKey',
                fieldName: 'API密钥',
                fieldType: 'password',
                required: true,
                placeholder: '请输入API密钥'
              }
            ]
          }
        ]
      }))
    }
  }
  return _channelConfigTemplates
}

// 为了向后兼容，保留原来的导出方式
export const channelConfigTemplates: ChannelConfigTemplate[] = new Proxy([], {
  get(target, prop) {
    const templates = getChannelConfigTemplates()
    return templates[prop as any]
  },
  has(target, prop) {
    const templates = getChannelConfigTemplates()
    return prop in templates
  },
  ownKeys(target) {
    const templates = getChannelConfigTemplates()
    return Reflect.ownKeys(templates)
  },
  getOwnPropertyDescriptor(target, prop) {
    const templates = getChannelConfigTemplates()
    return Reflect.getOwnPropertyDescriptor(templates, prop)
  }
})

// 获取渠道配置模板
export const getChannelConfigTemplate = (channelId: string): ChannelConfigTemplate | undefined => {
  return channelConfigTemplates.find(template => template.channelId === channelId)
}

// 根据渠道代码获取配置模板
export const getChannelConfigTemplateByCode = (channelCode: string): ChannelConfigTemplate | undefined => {
  return channelConfigTemplates.find(template => template.channelCode === channelCode)
}

// 基于协议动态生成渠道配置模板
export const generateChannelConfigTemplateFromProtocol = (channelCode: string): ChannelConfigTemplate | null => {
  try {
    const protocolId = protocol3Manager.getProtocolByConvention(channelCode, 'MERCHANT_CHANNEL_CONFIG_V3')
    const protocol = protocol3Manager.getProtocol(protocolId)
    if (!protocol) {
      throw new Error(`找不到渠道 ${channelCode} 的协议配置`)
    }
    const channel = paymentChannels.find(c => c.channelCode === channelCode)

    if (!channel) {
      console.warn(`找不到渠道信息: ${channelCode}`)
      return null
    }

    const template: ChannelConfigTemplate = {
      channelId: channel.channelId,
      channelName: protocol.channelName || channel.channelName,
      channelCode: channelCode,
      iconUrl: channel.iconUrl,
      description: protocol.description || `${channel.channelName}支付接口配置`,
      testConnection: true,
      configFields: generateConfigFields(channelCode)
    }

    return template
  } catch (error) {
    console.error(`生成渠道配置模板失败: ${channelCode}`, error)
    return null
  }
}

// 默认产品配置数据
export const defaultProductConfigs: ProductConfig[] = [
  {
    productId: 'PROD001',
    productName: '扫码支付',
    productCode: 'NATIVE',
    enabled: true,
    feeRate: 0.0060,
    minAmount: 0.01,
    maxAmount: 50000,
    dailyLimit: 1000000,
    monthlyLimit: 10000000,
    settlementCycle: 'T+1',
    description: '用户扫描商户二维码完成支付'
  },
  {
    productId: 'PROD002',
    productName: 'APP支付',
    productCode: 'APP',
    enabled: true,
    feeRate: 0.0060,
    minAmount: 0.01,
    maxAmount: 50000,
    dailyLimit: 1000000,
    monthlyLimit: 10000000,
    settlementCycle: 'T+1',
    description: '移动应用内调起支付'
  },
  {
    productId: 'PROD003',
    productName: '小程序支付',
    productCode: 'JSAPI',
    enabled: false,
    feeRate: 0.0060,
    minAmount: 0.01,
    maxAmount: 50000,
    dailyLimit: 500000,
    monthlyLimit: 5000000,
    settlementCycle: 'T+1',
    description: '小程序内支付'
  },
  {
    productId: 'PROD004',
    productName: 'H5支付',
    productCode: 'H5',
    enabled: false,
    feeRate: 0.0060,
    minAmount: 0.01,
    maxAmount: 50000,
    dailyLimit: 500000,
    monthlyLimit: 5000000,
    settlementCycle: 'T+1',
    description: '手机网页端支付'
  },
  {
    productId: 'PROD005',
    productName: '刷卡支付',
    productCode: 'MICROPAY',
    enabled: false,
    feeRate: 0.0060,
    minAmount: 0.01,
    maxAmount: 50000,
    dailyLimit: 200000,
    monthlyLimit: 2000000,
    settlementCycle: 'T+1',
    description: '商户扫描用户付款码完成支付'
  }
]

// 创建默认配置数据（支持channelId和channelCode）
export const createDefaultConfigData = (channelIdOrCode: string): Record<string, any> => {
  // 先尝试通过channelId获取
  let template = getChannelConfigTemplate(channelIdOrCode)

  // 如果没找到，尝试通过channelCode获取
  if (!template) {
    template = getChannelConfigTemplateByCode(channelIdOrCode)
  }

  // 如果还是没找到，尝试基于协议动态生成
  if (!template) {
    template = generateChannelConfigTemplateFromProtocol(channelIdOrCode)
  }

  if (!template) return {}

  const defaultData: Record<string, any> = {}
  template.configFields.forEach(field => {
    if (field.fieldType === 'select' && field.options && field.options.length > 0) {
      defaultData[field.fieldKey] = field.options[0].value
    } else {
      defaultData[field.fieldKey] = ''
    }
  })

  return defaultData
}

// 基于协议创建默认配置数据
export const createDefaultConfigDataFromProtocol = (channelCode: string): Record<string, any> => {
  try {
    const protocolId = protocol3Manager.getProtocolByConvention(channelCode, 'MERCHANT_CHANNEL_CONFIG_V3')
    const protocol = protocol3Manager.getProtocol(protocolId)
    if (!protocol) {
      throw new Error(`找不到渠道 ${channelCode} 的协议配置`)
    }

    const defaultData: Record<string, any> = {}

    // 从协议的配置分区中提取默认值
    for (const section of protocol.configSections) {
      // 合并分区的默认值
      if (section.defaultValues) {
        Object.assign(defaultData, section.defaultValues)
      }

      // 合并字段的默认值
      for (const field of section.fields) {
        if (field.defaultValue !== undefined) {
          defaultData[field.fieldKey] = field.defaultValue
        } else if (field.fieldType === FieldType.SELECT && field.options && field.options.length > 0) {
          defaultData[field.fieldKey] = field.options[0].value
        } else {
          defaultData[field.fieldKey] = ''
        }
      }
    }

    return defaultData
  } catch (error) {
    console.error(`创建默认配置失败: ${channelCode}`, error)
    return {}
  }
}


